import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/album_service.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/models/album_data_model.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/pages/album/album_item_page.dart';
import 'package:flutter_oldman_health/utils/event_bus.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';
import 'package:flutter_oldman_health/widget/edit_dialog.dart';

import 'album_item_delete_page.dart';

class AlbumPage extends StatefulWidget {
  AlbumPageState _state;

  @override
  AlbumPageState createState() {
    _state = AlbumPageState();
    return _state;
  }
}

class AlbumPageState extends State<AlbumPage> {
  Size screenSize;

  bool upLoadingData = false;
  bool isShowDialog = true;
  bool isLoadingData = false;
  String albumName, newAlbumId;
  List<String> albumListName = [];
  List<String> albumAllListName = [];
  List<AlbumModel> albumList = [];
  List<AlbumModel> myAlbumList = [];

  @override
  void initState() {
    super.initState();
    queryAlbumList();
    Utils.getIntSharePreferences("album_use_warning").then((value) {
      setState(() {
        isShowDialog = !(null != value && value > 0);
      });
    });

    EventBus().on("UploadCallbackEvent", (event) {
      print("eventbus UploadCallbackEvent ");
      setState(() {
        upLoadingData = event;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    EventBus().off("UploadCallbackEvent");
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    Future<void> _handleRefresh() async {
      bool load = await queryAlbumList();
      if (load) {
        EasyLoading.showSuccess('已刷新');
      }
    }

    return Scaffold(
        resizeToAvoidBottomInset: true,
        body: Container(
            color: Constant.backgroundColor,
            child: Column(children: [
              _getTitle(),
              if (upLoadingData) CommonContainer.uploadingView(),
              Stack(children: [
                if (!isLoadingData)
                  albumList.isNotEmpty
                      ? Container(
                          padding: EdgeInsets.fromLTRB(12, 0, 12, 0),
                          width: screenSize.width,
                          height: screenSize.height - 103,
                          child: RefreshIndicator(
                              onRefresh: _handleRefresh,
                              color: Colors.orange,
                              backgroundColor: Colors.white,
                              child: MediaQuery.removePadding(
                                  context: context,
                                  removeTop: true,
                                  child: GridView(
                                      gridDelegate:
                                          SliverGridDelegateWithFixedCrossAxisCount(
                                        childAspectRatio: 0.76,
                                        crossAxisCount: 2,
                                        mainAxisSpacing: 4,
                                        crossAxisSpacing: 4,
                                      ),
                                      children: _getListData()))))
                      : showListEmpty(),
                if (isShowDialog) getWarningDialog(),
                if (isLoadingData) CommonContainer.loadingView()
              ])
            ])));
  }

  Future<bool> queryAlbumList() async {
    setState(() {
      isLoadingData = true;
    });
    myAlbumList.clear();
    albumListName.clear();
    albumAllListName.clear();
    AlbumService.queryAlbumList().then((value) {
      setState(() {
        isLoadingData = false;
      });
      if (value != null && value.statusCode == 200) {
        AlbumDataModel albumDataModel = AlbumDataModel.fromJson(value.data);
        if (albumDataModel != null &&
            albumDataModel.success() &&
            albumDataModel.data != null) {
          setState(() {
            albumList = albumDataModel.data;
          });
          if (null != albumList && albumList.isNotEmpty) {
            albumList.forEach((element) {
              albumAllListName.add(element.name);

              if (element.myAlbum()) {
                myAlbumList.add(element);
                albumListName.add(element.name);
              }
            });
          }
        } else {
          EasyLoading.showInfo(albumDataModel.msg);
        }
      }

      return null != value && value.statusCode == 200;
    });
    return true;
  }

  void createAlbum(String name) {
    setState(() {
      isLoadingData = true;
    });
    AlbumService.createAlbum(name).then((value) {
      setState(() {
        isLoadingData = false;
      });
      if (value != null && value.statusCode == 200) {
        ResponseDataModel<String> response =
            ResponseDataModel.fromJson(value.data);
        if (response != null && response.success() && response.data != null) {
          newAlbumId = response.data;
          setState(() {
            AlbumModel album = AlbumModel(
                id: newAlbumId,
                name: name,
                creator: "我",
                inDate: DateTime.now().millisecondsSinceEpoch,
                photos: []);
            myAlbumList.add(album);
            albumList.add(album);
            albumListName.add(albumName);
            albumAllListName.add(albumName);
          });
          EasyLoading.showSuccess("创建相册成功");
        } else {
          EasyLoading.showInfo(response.msg);
        }
      }
    });
  }

  Widget showListEmpty() {
    return Align(
        alignment: Alignment.center,
        child: Column(children: [
          Padding(
            padding: EdgeInsets.only(top: 28),
            child: Image.asset('images/ic_album.png'),
          ),
          Padding(
            padding: EdgeInsets.only(top: 8, bottom: 16),
            child: Text(
                "与家人分享温情时刻"
                "\n点击右上角开始创建",
                style: TextStyle(fontSize: 18)),
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () async {
              albumName = await showDialog(
                  context: context,
                  builder: (context) => CustomEditDialog("新建相册", "", type: 1,allListName:albumAllListName));
              if (albumAllListName.contains(albumName)) {
                EasyLoading.showInfo("该相册名已存在");
                return;
              }

              if (albumName != null && albumName.length > 0) {
                if (albumName.replaceAll(" ", "") == " ") {
                  EasyLoading.showInfo("请勿创建空白相册名");
                  return;
                }
                createAlbum(albumName);
              }
            },
            child: Container(
                width: screenSize.width - 32,
                margin: EdgeInsets.all(16),
                padding: EdgeInsets.fromLTRB(16, 12, 16, 12),
                alignment: Alignment.center,
                child: Text("创建",
                    style: TextStyle(color: Colors.white, fontSize: 18)),
                decoration: BoxDecoration(
                    color: Colors.orange,
                    borderRadius: BorderRadius.all(Radius.circular(18)))),
          )
        ]));
  }

  showAlbumOperation() async {
    showDialog(
        context: context,
        builder: (context) {
          return SimpleDialog(children: [
            GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  Navigator.pop(context);

                  albumName = await showDialog(
                      context: context,
                      builder: (context) =>
                          CustomEditDialog("新建相册", "", type: 1,allListName:albumAllListName));
                  if (albumAllListName.contains(albumName)) {
                    EasyLoading.showInfo("该相册名已存在");
                    return;
                  }
                  if (albumName != null && albumName.length > 0) {
                    if (albumName.replaceAll(" ", "") == "") {
                      EasyLoading.showInfo("请勿创建空白相册名");
                      return;
                    }
                    createAlbum(albumName);
                  }
                },
                child: Container(
                    padding: EdgeInsets.all(12),
                    alignment: Alignment.center,
                    child: Text("创建相册", style: TextStyle(fontSize: 17)))),
            if (myAlbumList.isNotEmpty)
              Divider(height: 1, indent: 16, endIndent: 16),
            if (myAlbumList.isNotEmpty)
              GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () async {
                    Navigator.pop(context);

                    bool change = await Navigator.push(context,
                        MaterialPageRoute(builder: (context) {
                      return AlbumItemDeletePage(myAlbumList);
                    }));
                    if (change) {
                      queryAlbumList();
                    }
                  },
                  child: Container(
                      padding: EdgeInsets.all(12),
                      alignment: Alignment.center,
                      child: Text("删除相册",
                          style: TextStyle(color: Colors.red, fontSize: 17)))),
            Divider(height: 1, indent: 16, endIndent: 16),
            Container(
                margin: EdgeInsets.fromLTRB(12, 12, 12, 0),
                child: ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                        padding: EdgeInsets.all(12), child: Text("取消")),
                    style: ButtonStyle(
                        shape: MaterialStateProperty.all(StadiumBorder(
                            side: BorderSide(
                                //设置 界面效果 圆角弧度
                                style: BorderStyle.none,
                                color: Colors.orange))),
                        backgroundColor:
                            MaterialStateProperty.all(Colors.orange),
                        textStyle: MaterialStateProperty.all(
                            TextStyle(fontSize: 17)))))
          ]);
        });
  }

  void showAddAlbumDialog() {
    showDialog(
        context: context,
        builder: (context) {
          return getWarningDialog();
        });
  }

  void showWarningDialog() {
    showDialog(
        context: context,
        builder: (context) {
          return getWarningDialog();
        });
  }

  Widget getImageWidget(String imgUrl) {
    return Card(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadiusDirectional.circular(8)),
        clipBehavior: Clip.antiAlias,
        child: imgUrl != null
            ? CachedNetworkImage(
                width: double.maxFinite,
                height: screenSize.width / 2 - 20,
                fit: BoxFit.cover,
                imageUrl: imgUrl,
                placeholder: (context, url) => assetImage(),
                // CommonContainer.loadingView(h: 100),
                errorWidget: (context, url, error) => assetImage(),
              )
            : assetImage());
  }

  Widget assetImage() {
    return Image.asset('images/ic_album.png',
        width: double.maxFinite,
        height: screenSize.width / 2 - 20,
        fit: BoxFit.cover);
  }

  List<Widget> _getListData() {
    var tempList = albumList.map((e) => GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () async {
          print('${e.id} ${e.creator}');
          int needRefresh = await Navigator.push(context,
              MaterialPageRoute(builder: (context) {
            return AlbumItemPage(e, widget,albumAllListName);
          }));
          if (needRefresh != null && needRefresh > 0) {
            queryAlbumList();
          }
        },
        child: Stack(children: [
          getImageWidget((e.photos != null && e.photos.length > 0)
              ? e.photos[0].location
              : null),
          Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                  width: double.maxFinite,
                  height: 55,
                  padding: EdgeInsets.only(left: 8),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(e.name,
                            maxLines: 1, style: TextStyle(fontSize: 17)),
                        Text("创建人：${e.creator}",
                            maxLines: 1,
                            style: TextStyle(
                                fontSize: 12, color: Color(0xaa333333)))
                      ])))
        ])));
    return tempList.toList();
  }

  Widget _getTitle([String title = "相册"]) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 16),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                left: 2,
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Container(
                      child: Icon(Icons.arrow_back_ios),
                      padding: EdgeInsets.fromLTRB(15, 10, 20, 10)),
                ),
              ),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal)),
              Positioned(
                  right: 2,
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        showAlbumOperation();
                      },
                      child: Icon(Icons.more_horiz_sharp, size: 28)))
            ],
          ),
        ));
  }

  Widget getWarningDialog() {
    return AlertDialog(
        title: Text(
          "温馨提示",
          textAlign: TextAlign.center,
          style: TextStyle(color: Colors.orange),
        ),
        content: Text(
            "1.上传到家庭相册中的照片会被适当压缩"
            "\n2.创建的相册将会共享给所有已绑定的亲友"
            "\n3.创建相册者可以对相册中的照片进行删除"
            "\n4.非相册创建人只能对相册中的照片进行查看，不能删除",
            style: TextStyle(fontSize: 17, color: Color(0xff666666))),
        actions: <Widget>[
          Row(
            children: [
              Expanded(
                  child: OutlinedButton(
                      onPressed: () {
                        setState(() {
                          isShowDialog = false;
                          Navigator.pop(context);
                        });
                      },
                      child: Padding(
                          padding: EdgeInsets.all(8), child: Text("暂时不用")),
                      style: ButtonStyle(
                          shape: MaterialStateProperty.all(StadiumBorder(
                              side: BorderSide(
                            //设置 界面效果 圆角弧度
                            style: BorderStyle.solid,
                            color: Color(0xffFFffff),
                          ))),
                          foregroundColor:
                              MaterialStateProperty.all(Color(0xff666666)),
                          textStyle: MaterialStateProperty.all(
                              TextStyle(fontSize: 17)))),
                  flex: 1),
              Padding(padding: EdgeInsets.all(8)),
              Expanded(
                  child: ElevatedButton(
                      onPressed: () {
                        setState(() {
                          Utils.putIntSharePreferences("album_use_warning", 1);
                          isShowDialog = false;
                        });
                      },
                      child: Padding(
                          padding: EdgeInsets.all(8), child: Text("继续使用")),
                      style: ButtonStyle(
                          shape: MaterialStateProperty.all(StadiumBorder(
                              side: BorderSide(
                            //设置 界面效果 圆角弧度
                            style: BorderStyle.solid,
                          ))),
                          backgroundColor:
                              MaterialStateProperty.all(Colors.orange),
                          textStyle: MaterialStateProperty.all(
                              TextStyle(fontSize: 17)))),
                  flex: 1)
            ],
          )
        ]);
  }

  showAlbumOperation2() async {
    Scaffold.of(context).showBottomSheet((context) {
      return Column(children: []);
    });
  }
}
